package org.example.common.social.maxkey;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.lang.Dict;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.enums.AuthResponseStatus;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.log.Log;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthDefaultRequest;
import org.example.common.core.utils.SpringUtils;
import org.example.common.core.utils.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.spec.AlgorithmParameterSpec;

/**
 * 微信小程序登录
 *  @author wangkai
 */
public class AuthWechatAppletRequest extends AuthDefaultRequest {

    public static final String SERVER_URL = SpringUtils.getProperty("justauth.type.wechatApplet.service-url");
    private final static String LOGINURL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

    private AuthConfig config;
    /**
     * 设定归属域
     */
    public AuthWechatAppletRequest(AuthConfig config) {
        super(config, AuthWechatAppletSource.WECHAT_APPLET);
        this.config=config;
    }

    public AuthWechatAppletRequest(AuthConfig config, AuthStateCache authStateCache) {
        super(config, AuthWechatAppletSource.WECHAT_APPLET, authStateCache);
        this.config=config;
    }
    @Override
    public AuthResponse login(AuthCallback authCallback) {
        try {
            String state=  authCallback.getState();
            JSONObject vo=JSON.parseObject(state);
            if(vo.containsKey("isAuth")){
                if(vo.getBoolean("isAuth")){
                    byte[] encrypData = Base64.decode(vo.getString("encryp_data"));
                    byte[] ivData = Base64.decode(vo.getString("iv_data"));
                    byte[] sessionKey = Base64.decode(vo.getString("session_key"));
                    String str = decrypt(sessionKey, ivData, encrypData);
                    if(StringUtils.isEmpty(str)){
                        return AuthResponse.builder().code(AuthResponseStatus.FAILURE.getCode()).msg("授权登录失败").build();
                    }
                    JSONObject result = JSON.parseObject(str);
                    AuthUser authUser= AuthUser.builder()
                            .uuid(authCallback.getCode())
                            .username(StringUtils.defaultString(result.getString("phoneNumber"),
                                    result.getString("purePhoneNumber")))
                            .source(source.toString())
                            .build();
                    return AuthResponse.builder().code(AuthResponseStatus.SUCCESS.getCode()).data(authUser).build();
                }
                AuthUser authUser= AuthUser.builder()
                        .uuid(authCallback.getCode())
                        .source(source.toString())
                        .build();
                return AuthResponse.builder().code(AuthResponseStatus.SUCCESS.getCode()).data(authUser).build();
            }
            return AuthResponse.builder().code(AuthResponseStatus.FAILURE.getCode()).msg("授权登录失败").build();
        } catch (Exception var4) {
            Log.error("Failed to login with oauth authorization.", var4);
            return AuthResponse.builder().code(AuthResponseStatus.FAILURE.getCode()).msg("授权登录失败").build();
        }
    }

    public static String decrypt(byte[] key, byte[] iv, byte[] encData) throws Exception {
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        //解析解密后的字符串
        return new String(cipher.doFinal(encData), "UTF-8");
    }


    @Override
    protected AuthToken getAccessToken(AuthCallback authCallback) {
        String body = doPostAuthorizationCode(authCallback.getCode());
        Dict object = JSON.parseObject(body,Dict.class);
        // oauth/token 验证异常
        if (object.containsKey("error")) {
            throw new AuthException(object.getStr("error_description"));
        }
        // user 验证异常
        if (object.containsKey("message")) {
            throw new AuthException(object.getStr("message"));
        }
        return AuthToken.builder()
            .accessToken(object.getStr("access_token"))
            .refreshToken(object.getStr("refresh_token"))
            .idToken(object.getStr("id_token"))
            .tokenType(object.getStr("token_type"))
            .scope(object.getStr("scope"))
            .build();
    }

    @Override
    protected AuthUser getUserInfo(AuthToken authToken) {
        String body = doGetUserInfo(authToken);
        Dict object = JSON.parseObject(body,Dict.class);
        // oauth/token 验证异常
        if (object.containsKey("error")) {
            throw new AuthException(object.getStr("error_description"));
        }
        // user 验证异常
        if (object.containsKey("message")) {
            throw new AuthException(object.getStr("message"));
        }
        return AuthUser.builder()
            .uuid(object.getStr("userId"))
            .username(object.getStr("username"))
            .nickname(object.getStr("displayName"))
            .avatar(object.getStr("avatar_url"))
            .blog(object.getStr("web_url"))
            .company(object.getStr("organization"))
            .location(object.getStr("location"))
            .email(object.getStr("email"))
            .remark(object.getStr("bio"))
            .token(authToken)
            .source(source.toString())
            .build();
    }

}
